﻿<template>
  <view class="container">
    <!-- 任务状态提示区域 -->
    <view class="status-tip-area" v-if="!isCompleted && !isCancelled">
      <view class="status-tip">
        <text class="status-icon" :class="taskStatus">{{ getStatusIcon(taskStatus) }}</text>
        <text class="status-text">{{ getTaskStatusText(taskStatus) }}</text>
        <text v-if="isProcessing" class="time-left">{{ getRemainingTime() }}</text>
      </view>
    </view>

    <!-- 状态时间信息 -->
    <view class="status-time" v-if="!isPending">{{ formatStatusTime() }}</view>
    
    <!-- 待验收状态提示 -->
    <view class="review-tip" v-if="isPendingReview">
      <text class="tip-icon">🔍</text>
      <text class="tip-text">任务已提交，等待发布者验收和评价</text>
    </view>

    <!-- 任务信息区域 -->
    <view class="task-info">
      <!-- 标题和类型容器-->
      <view class="task-header-flex">
        <view class="task-title">
          <template v-if="task.type === 'buy'">求购 - {{ task.title }}</template>
          <template v-else-if="task.type === 'sell'">{{ task.title }}</template>
          <template v-else-if="['express', 'takeout'].includes(task.type)">{{ task.title }} - {{ task.pickupAddress }}</template>
          <template v-else>{{ task.title }}</template>
        </view>
        <view class="task-type-container">
          <view class="task-type">
            <text class="type-tag" :class="task.type">{{ getTaskTypeText(task.type) }}</text>
            <text v-if="task.tags && task.tags.includes('加急')" class="urgent-tag">加急</text>
            <text class="task-status-tag" :class="task.status">
              {{ getTaskStatusText(task.status) }}
            </text>
          </view>
        </view>
      </view>
      <view class="task-time">
        <text class="time-label">发布时间：</text>
        <text class="time-value">{{ formatPublishTime(task.publishTime) }}</text>
      </view>
      <!-- 期望送达时间 - 仅在快递或外卖显示 -->
      <view class="task-time" v-if="task.expectedDeliveryTime">
  <text class="time-label">
    <!-- 根据任务类型动态显示标签文字 -->
    {{ ['express', 'takeout'].includes(task.type) ? '期望送达时间：' : '期望完成时间：' }}
  </text>
  <text class="time-value">{{ task.expectedDeliveryTime }}</text>
</view>
      <view class="task-reward">
        <text class="reward-label">赏金：</text>
        <text class="reward-value">{{ task.reward }}</text>
      </view>
       <!-- 商品成色 - 在出物和求购任务显示 -->
      <view class="task-time" v-if="['sell', 'buy'].includes(task.type)">
        <text class="time-label">商品成色：</text>
        <text class="time-value">{{ getConditionText(task.selectedCondition) }}</text>
      </view>
    </view>

    <!-- 进行中状态专属区域 -->
    <view class="processing-area" v-if="isProcessing">
      <view class="section-title">任务进度</view>
      <view class="progress-steps" :style="{ '--progress-width': progressBarWidth }">
        <view class="step-item" :class="{ active: step <= progressStep }" v-for="(step, index) in taskSteps" :key="index">
          <view class="step-icon">{{ step.icon }}</view>
          <view class="step-text">{{ step.text }}</view>
        </view>
      </view>
      <view class="progress-actions">
        <!-- 接单者可见：更新进度 + 联系发布者 -->
        <button v-if="isClaimer" class="action-button update" @tap="updateProgress">更新进度</button>
        <button v-if="isClaimer" class="action-button contact" @tap="contactPublisher">联系发布者</button>
        
        <!-- 发布者可见：提醒接单者 + 查看接单者信息 -->
        <button v-if="isPublisher" class="action-button remind" @tap="remindClaimer">提醒接单者</button>
        <button v-if="isPublisher" class="action-button view-claimer" @tap="viewClaimerInfo">查看接单者</button>
      </view>
    </view>

 <!-- 图片轮播区域 -->
 <view class="image-slider" v-if="task.images && task.images.length > 0 && ['buy', 'sell', 'takeout'].includes(task.type)">
      <swiper :indicator-dots="true" :autoplay="false" :interval="3000" :duration="500">
        <swiper-item v-for="(image, index) in task.images" :key="index">
          <image :src="image" mode="aspectFill" class="slider-image" @error="handleImageError" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 任务描述区域 -->
    <view class="description-section" v-if="task.type !== 'other'">
      <view class="section-title">具体说明</view>
      <view class="description-text">{{ task.description }}</view>
    </view>

    <!-- 具体信息区域 - 快递和外卖显示地址信息，出物不显示 -->
    <view class="address-section" v-if="['express', 'takeout'].includes(task.type)">
      <view class="section-title">地址信息</view>
      <view class="address-item">
        <view class="address-label">取件地址：</view>
        <view class="address-content">
          <text class="address-text">{{ task.pickupAddress }}</text>
          <button class="copy-btn" @tap="copyPickupAddress">复制</button>
          <button class="nav-btn" @tap="navigateToPickup">导航</button>
        </view>
      </view>
      <!-- 快递单号，仅在快递代取任务显示-->
      <view class="address-item" v-if="task.type === 'express'">
        <view class="address-label">快递单号：</view>
        <view class="address-content">
          <text class="address-text">{{ task.trackingNumber }}</text>
          <button class="copy-btn" @tap="copyTrackingNumber">复制</button>
        </view>
      </view>
      <view class="address-item">
        <view class="address-label">送达地址：</view>
        <view class="address-content">
          <text class="address-text">{{ task.deliveryAddress }}</text>
          <button class="copy-btn" @tap="copyDeliveryAddress">复制</button>
          <button class="nav-btn" @tap="navigateToDelivery">导航</button>
        </view>
      </view>
    </view>

    <!-- 联系人信息区域-->
    <view class="publisher-section">
      <view class="section-title">{{ task.type === 'express' ? '收件人信息' : '联系信息' }}</view>
      <view class="publisher-info">
        <!-- 仅在快递代取或出物或求购或外卖代拿任务显示联系人姓名和电话 -->
        <view class="publisher-details" v-if="['express', 'sell', 'buy', 'takeout', 'other'].includes(task.type)">
          <!-- 发布者可以看到完整信息-->
          <template v-if="isPublisher">
            <text class="contact-info">{{ ['express', 'takeout'].includes(task.type) ? '收件人姓名' : '联系人姓名' }}：{{ task.contactName }}</text>
            <text class="contact-info">联系电话：{{ task.contactPhone }}</text>
          </template>
          <!-- 接单者可以看到完整信息-->
          <template v-else-if="isClaimer">
            <text class="contact-info">{{ ['express', 'takeout'].includes(task.type) ? '收件人姓名' : '联系人姓名' }}：{{ task.contactName }}</text>
            <text class="contact-info">联系电话：{{ task.contactPhone }}</text>
          </template>

          <!-- 普通用户只能看到部分信息-->
          <template v-else>
            <text class="contact-info">{{ ['express', 'takeout'].includes(task.type) ? '收件人姓名' : '联系人姓名' }}：{{ task.contactName }}</text>
            <text class="contact-info">联系电话：接单后可见</text>
            <text class="privacy-tip">* 为保护发布者隐私，接单后可见完整联系方式</text>
          </template>
        </view>
        <!-- 其他任务类型显示发布者信息-->
        <view class="publisher-details" v-else>
          <image :src="task.publisher.avatar" class="publisher-avatar" />
          <text class="publisher-name">{{ task.publisher.nickname }}</text>
          <text class="publisher-rating">信用等级：{{ task.publisher.creditRating }}</text>
        </view>
      </view>
    </view>


    <!-- 底部操作栏-->
    <view class="bottom-bar">
      <view class="action-buttons">
        <!-- 接单按钮：仅任务状态为pending且不是发布者和接单者时显示 -->
        <button 
          v-if="showClaimButton" 
          class="action-button confirm" 
          @tap="confirmClaimTask"
        >
          确认接单
        </button>
        <button 
          v-if="showClaimButton" 
          class="action-button ignore" 
          @tap="goBack"
        >
          暂不考虑
        </button>

        <!-- 进行中状态操作按钮 -->
        <button 
          v-if="showCompleteButton" 
          class="action-button complete" 
          @tap="completeTask"
        >
          完成任务
        </button>

        <!-- 发布者视角：沿用原有逻辑 -->
        <button 
          v-if="isPublisher && showStartButton" 
          class="action-button start" 
          @tap="startTask"
        >
          发布任务
        </button>
        <button 
          v-if="showCancelButton" 
          class="action-button cancel" 
          @tap="cancelTask"
        >
          取消任务
        </button>

        <!-- 完成状态评价按钮 -->
        <button 
          v-if="showEvaluateButton" 
          class="action-button evaluate" 
          @tap="showEvaluateDialog"
        >
          评价任务
        </button>
      </view>
    </view>

    <!-- 评价弹窗 -->
    <view class="evaluate-modal" v-if="showEvaluate">
      <view class="modal-content">
        <view class="modal-title">评价任务</view>
        <view class="star-rating">
          <text class="star" v-for="i in 5" :key="i" :class="{ selected: i <= rating }" @tap="rating = i">★</text>
        </view>
        <textarea class="evaluate-input" placeholder="请输入评价内容..." v-model="evaluationContent"></textarea>
        <view class="modal-buttons">
          <button class="modal-btn cancel" @tap="showEvaluate = false">取消</button>
          <button class="modal-btn confirm" @tap="submitEvaluation">提交评价</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentUserRole: 'user',
      taskId: '',
      taskData: null,
      timer: null,
      showEvaluate: false,
      rating: 5,
      evaluationContent: '',
      evaluated: false,
      showReEvaluate: false,
      progressStep: 3,
      steps: [
        { icon: '📦', text: '已接单' },
        { icon: '🏃', text: '前往取件' },
        { icon: '✅', text: '已取件' },
        { icon: '🚚', text: '配送中' },
        { icon: '🎉', text: '已完成' }
      ],
      task: {
        id: '',
        type: '',
        status: '',
        title: '',
        description: '',
        reward: 0,
        publishTime: '',
        expectedDeliveryTime: '',
        pickupAddress: '',
        deliveryAddress: '',
        trackingNumber: '',
        recipientName: '',
        contactName: '',
        contactPhone: '',
        selectedCondition: '',
        images: [],
        publisher: {
          id: '',
          nickname: '',
          avatar: '',
          creditRating: 0
        },
        receiver: null,
        acceptTime: '',
        completeTime: '',
        cancelTime: ''
      }
    }
  },

  computed: {
    // 统一管理状态相关计算属性
    taskStatus() {
      return this.task.status || 'pending';
    },
    isPending() { return this.taskStatus === 'pending'; },
    isProcessing() { return this.taskStatus === 'processing'; },
    isPendingReview() { return this.taskStatus === 'pending_review'; },
    isCompleted() { return this.taskStatus === 'completed'; },
    isCancelled() { return this.taskStatus === 'cancelled'; },

    isPublisher() {
      return this.currentUserRole === 'publisher';
    },
    isClaimer() {
      return this.currentUserRole === 'claimer';
    },

    // 优化后的按钮显示逻辑
    showClaimButton() {
      return this.isPending && !this.isPublisher && !this.isClaimer;
    },
    showCancelButton() {
      return (this.isPending || this.isProcessing) && this.isPublisher;
    },
    showCompleteButton() {
      return this.isProcessing && this.isClaimer;
    },
    showStartButton() {
      return this.isPublisher && this.task.status === 'pending';
    },
    showEvaluateButton() {
      // 仅发布者可评价，且任务状态为待验收
      return this.isPublisher && this.isPendingReview;
    },
    
    // 判断是否可以接单
    canClaimTask() {
      // 基本条件：任务状态为pending，用户不是发布者，用户不是接单者
      return this.isPending && !this.isPublisher && !this.isClaimer;
    },
    
    // 根据任务类型获取进度步骤
    taskSteps() {
      const stepMap = {
      'express': [ // 快递代取：贴合“取件-配送”流程
        { icon: '📦', text: '已接单' },
        { icon: '🏃', text: '前往快递站' },
        { icon: '✅', text: '确认快递' },
        { icon: '🚚', text: '配送中' },
        { icon: '🎉', text: '已送达' }
      ],
      'takeout': [ // 外卖代拿：贴合“取餐-送餐”流程
        { icon: '📦', text: '已接单' },
        { icon: '🏃', text: '前往餐厅' },
        { icon: '✅', text: '取餐完成' },
        { icon: '🚚', text: '配送中' },
        { icon: '🎉', text: '已送达' }
      ],
      'buy': [ // 求购任务：贴合“找货-交易”流程
        { icon: '📦', text: '已接单' },
        { icon: '🔍', text: '寻找商品' },
        { icon: '💴', text: '确认购买' },
        { icon: '📥', text: '商品到手' },
        { icon: '🎉', text: '交易完成' }
      ],
      'sell': [ // 出物任务：贴合“展示-交付”流程
        { icon: '📦', text: '已接单' },
        { icon: '🖼️', text: '商品展示' },
        { icon: '💬', text: '协商价格' },
        { icon: '📤', text: '商品交付' },
        { icon: '🎉', text: '交易完成' }
      ],
      'other': [ // 其他任务：通用流程
        { icon: '📦', text: '已接单' },
        { icon: '🏃', text: '开始处理' },
        { icon: '⏳', text: '进行中' },
        { icon: '⚠️', text: '即将完成' },
        { icon: '🎉', text: '任务完成' }
      ]
    };
      return stepMap[this.task.type] || stepMap['other'];
    },
    
    // 计算进度条宽度
    progressBarWidth() {
      if (!this.taskSteps || this.taskSteps.length === 0) return '0%';
      const progress = (this.progressStep - 1) / (this.taskSteps.length - 1);
      return Math.max(0, Math.min(100, progress * 100)) + '%';
    }
  },

  methods: {
     // 提醒接单者（发布者调用）
  remindClaimer() {
    if (!this.task.receiver || !this.task.receiver.id) {
      uni.showToast({ title: '未找到接单者信息', icon: 'none' });
      return;
    }
    // 实际项目中可调用云函数发送消息提醒
    uni.showModal({
      title: '提醒接单者',
      content: '确定要发送进度提醒给接单者吗？',
      success: (res) => {
        if (res.confirm) {
          // 模拟发送提醒
          uni.showToast({ title: '已提醒接单者', icon: 'success' });
          // 真实场景：调用云函数推送消息给接单者
          /*
          uniCloud.callFunction({
            name: 'sendReminder',
            data: { taskId: this.task.id, receiverId: this.task.receiver.id }
          });
          */
        }
      }
    });
  },
  
  // 查看接单者信息（发布者调用）
  viewClaimerInfo() {
    if (!this.task.receiver) {
      uni.showToast({ title: '未找到接单者信息', icon: 'none' });
      return;
    }
    // 显示接单者详情（可跳转到详情页或弹窗展示）
    uni.showModal({
      title: '接单者信息',
      content: `昵称：${this.task.receiver.nickname || '未知'}\n信用等级：${this.task.receiver.creditRating || '暂无'}`,
      showCancel: false
    });
  },
    getCurrentUser() {
      const userInfo = uni.getStorageSync('uni-id-pages-userInfo');
      if (userInfo) {
        return {
          id: userInfo._id,
          nickname: userInfo.nickname,
          avatar: (userInfo.avatar_file && userInfo.avatar_file.url) ? userInfo.avatar_file.url : '/static/images/avatar1.png'
        };
      } else {
        return null; // 用户未登录
      }
    },

    getRole(task, user) {
  // 基础容错：任务/用户不存在直接返回普通用户
  if (!task || !user || !user.id || typeof user.id !== 'string') {
    console.log('[getRole] 基础数据缺失，返回普通用户');
    return 'user';
  }

  // 统一ID格式（避免字符串/数字类型不匹配）
  const userId = user.id.trim();
  const publisherId = task.publisher?.id ? task.publisher.id.trim() : '';
  const receiverId = task.receiver?.id ? task.receiver.id.trim() : '';

  // 详细日志：便于调试ID匹配问题
  console.log('[getRole] 匹配日志:', {
    userId,
    publisherId,
    receiverId,
    isPublisher: userId === publisherId,
    isReceiver: userId === receiverId,
    taskStatus: task.status,
    taskId: task.id
  });

  // 优先级：发布者 > 接单者 > 普通用户
  if (userId === publisherId) return 'publisher';
  if (userId === receiverId) return 'claimer';
  return 'user';
},

determineUserRole() {
  const user = this.getCurrentUser();
  console.log('[determineUserRole] 开始判断角色...');
  console.log('[determineUserRole] 当前用户:', user);
  console.log('[determineUserRole] 当前任务:', this.task);
  
  // 先校验用户登录状态
  if (!user || !user.id) {
    this.currentUserRole = 'user';
    console.log('[determineUserRole] 用户未登录，角色设为普通用户');
    return;
  }

  // 校验任务数据完整性（至少包含发布者信息）
  if (!this.task || !this.task.publisher) {
    console.log('[determineUserRole] 任务数据不完整，暂设为普通用户');
    console.log('[determineUserRole] task:', this.task);
    console.log('[determineUserRole] publisher:', this.task?.publisher);
    this.currentUserRole = 'user';
    // 延迟重试（等待任务数据加载）
    setTimeout(() => this.determineUserRole(), 300);
    return;
  }

  // 执行角色判断并更新
  const newRole = this.getRole(this.task, user);
  console.log(`[determineUserRole] 角色判断结果: ${newRole}`);
  
  if (this.currentUserRole !== newRole) {
    console.log(`[determineUserRole] 角色更新：${this.currentUserRole} → ${newRole}`);
    this.currentUserRole = newRole;
    // 角色变化后触发按钮状态刷新（如接单后显示"完成任务"按钮）
    this.$forceUpdate();
  } else {
    console.log(`[determineUserRole] 角色未变化: ${this.currentUserRole}`);
  }
},

    getTaskTypeText(type) {
      const typeMap = {
        'express': '快递代取',
        'takeout': '外卖代拿',
        'buy': '求购',
        'sell': '出物',
        'other':'其他'
      };
      return typeMap[type] || type;
    },

    getConditionText(condition) {
      const conditionMap = {
        'new': '全新',
        'like-new': '九成新',
        'good': '八成新',
        'fair': '七成新'
      };
      return conditionMap[condition] || '';
    },

    getTaskStatusText(status) {
      const statusMap = {
        'pending': '待接单',
        'processing': '进行中',
        'pending_review': '待验收',
        'completed': '已完成',
        'cancelled': '已取消'
      };
      return statusMap[status] || status;
    },

    getStatusIcon(status) {
      const iconMap = {
        'pending': '⏳',
        'processing': '🚀',
        'pending_review': '🔍',
        'completed': '✅',
        'cancelled': '❌'
      };
      return iconMap[status] || '❓';
    },

    navigateToPickup() {
      console.log('导航到取件地址:', this.task.pickupAddress);
      // 实际项目中调用地图导航API
      uni.showToast({
        title: '正在导航到取件地址',
        icon: 'none'
      });
    },

    navigateToDelivery() {
      console.log('导航到送达地址:', this.task.deliveryAddress);
      // 实际项目中调用地图导航API
      uni.showToast({
        title: '正在导航到送达地址',
        icon: 'none'
      });
    },

    copyPickupAddress() {
      uni.setClipboardData({
        data: this.task.pickupAddress,
        success: () => {
          uni.showToast({
            title: '取件地址已复制',
            icon: 'success'
          });
        }
      });
    },

    copyDeliveryAddress() {
      uni.setClipboardData({
        data: this.task.deliveryAddress,
        success: () => {
          uni.showToast({
            title: '送达地址已复制',
            icon: 'success'
          });
        }
      });
    },

    copyTrackingNumber() {
      uni.setClipboardData({
        data: this.task.trackingNumber,
        success: () => {
          uni.showToast({
            title: '快递单号已复制',
            icon: 'success'
          });
        }
      });
    },

    handleImageError(e) {
      console.error('图片加载失败:', e);
      uni.showToast({
        title: '图片加载失败',
        icon: 'none'
      });
    },

    getFormattedTitle(task) {
      if (!task) return '未知任务';
      
      switch (task.type) {
        case 'buy':
          return `求购${task.itemName || ''}${task.selectedCondition ? `(${this.getConditionText(task.selectedCondition)})` : ''}`;
        case 'express':
          return `${task.pickupAddress || ''}快递代取`;
        case 'sell':
          return `出售${task.selectedCondition ? this.getConditionText(task.selectedCondition) : ''}${task.itemName || ''}`;
        case 'takeout':
          return `${task.pickupAddress || ''}外卖代拿`;
        default:
          return task.title || '未知任务';
      }
    },

    startTask() {
      if (this.task) {
        // 使用传入的task.id，如果不存在则生成一个新的
        const taskId = this.task.id || 'task_' + Date.now().toString();
        const currentUser = this.getCurrentUser();
        
        if (!currentUser) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          });
          return;
        }

        // 验证必要字段
        if (!this.task.itemName && this.task.type === 'buy') {
          uni.showToast({
            title: '物品名称不能为空',
            icon: 'none'
          });
          return;
        }

        if (!this.task.pickupAddress && (this.task.type === 'express' || this.task.type === 'takeout')) {
          uni.showToast({
            title: '取件地址不能为空',
            icon: 'none'
          });
          return;
        }

        // 构建任务数据，添加默认值和数据验证
        const taskData = {
          id: taskId,
          type: this.task.type || 'unknown',
          title: this.getFormattedTitle(this.task),
          itemName: this.task.itemName || '',
          selectedCondition: this.task.selectedCondition || '',
          pickupAddress: this.task.pickupAddress || '',
          deliveryAddress: this.task.deliveryAddress || '',
          price: this.task.price || 0,
          description: this.task.description || '',
          images: this.task.images || [],
          status: 'pending',
          createTime: new Date().toISOString(),
          publisher: {
            id: currentUser._id,
            nickname: currentUser.nickname || '匿名用户',
            avatar: (currentUser.avatar_file && currentUser.avatar_file.url) || '/static/images/avatar1.png'
          }
        };

        console.log('[TaskDetail.vue] 即将发布任务数据:', taskData);
        uni.$emit('newTaskPublished', taskData);
        uni.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 2000
        });

        setTimeout(() => {
          uni.redirectTo({
            url: '/pages/index/index',
            success: () => {
              console.log('跳转到首页成功');
              try {
                const existingTasks = uni.getStorageSync('myTasks') || '[]';
                const tasks = JSON.parse(existingTasks);
                const myTasksExistingIndex = tasks.findIndex(t => t.id === taskData.id);
                if (myTasksExistingIndex === -1) {
                tasks.unshift(taskData);
                uni.setStorageSync('myTasks', JSON.stringify(tasks));
                    console.log('任务已保存到本地存储 myTasks');
                } else {
                    console.log('任务已存在于 myTasks，跳过添加');
                }
              } catch (error) {
                console.error('保存任务到本地存储 myTasks 失败:', error);
              }
            },
            fail: (err) => {
              console.error('跳转失败:', err);
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              });
            }
          });
        }, 1500);
      } else {
        console.warn('任务数据为空');
        uni.showToast({
          title: '任务数据获取失败',
          icon: 'none'
        });
      }
    },

    cancelTask() {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消此任务吗？取消后将无法恢复。',
        confirmText: '确认取消',
        cancelText: '再想想',
        success: async (res) => {
          if (res.confirm) {
            this.handleStatusChange('cancelled');
          }
        }
      });
    },

    completeTask() {
      // 验证任务状态
      if (this.task.status !== 'processing') {
          uni.showToast({
          title: '只有进行中的任务可以完成',
            icon: 'none'
          });
          return;
      }

      // 验证当前用户权限
      if (!this.isClaimer) {
        uni.showToast({
          title: '只有接单者可以完成任务',
          icon: 'none'
        });
        return;
      }

      uni.showModal({
        title: '完成任务',
        content: '确认已完成此任务吗？提交后将通知发布者进行验收。',
        confirmText: '确认完成',
        cancelText: '取消',
        success: async (res) => {
          if (res.confirm) {
            // 显示加载状态
            uni.showLoading({ title: '提交中...' });
            
            try {
              // 1. 获取当前用户信息
              const currentUser = this.getCurrentUser();
              if (!currentUser || !currentUser.id) {
                throw new Error('用户信息获取失败，请重新登录');
              }

              // 【修改点2】调用云函数发送任务完成通知给发布者
              const noticeResult = await uniCloud.callFunction({
                name: 'createTaskNotification',
                data: {
                  userId: this.task.publisher.id, // 接收通知的用户ID（发布者）
                  taskId: this.task.id,
                  taskTitle: this.task.title,
                  status: 'completed', // 对应通知类型
                  actionUserId: currentUser.id, // 执行操作的用户ID（接单者）
                  actionUserNickname: currentUser.nickname || '用户'
                }
              });

              // 检查通知是否发送成功
              if (!noticeResult.result || !noticeResult.result.success) {
                console.warn('通知发送失败，但仍继续完成任务流程', noticeResult.result);
                // 不中断流程，仅提示警告
                uni.showToast({
                  title: '任务完成通知发送失败',
                  icon: 'none',
                  duration: 2000
                });
              }

              // 3. 更新任务状态为待验收（发布者需要验收和评价）
              await this.handleStatusChange('pending_review');

              // 4. 显示成功提示
              uni.hideLoading();
              uni.showToast({
                title: '任务已提交，等待发布者验收',
                icon: 'success',
                duration: 2000
              });

              // 【修改点3】延迟跳转至我的任务页面
              setTimeout(() => {
      uni.navigateTo({
                  url: '/pages/user/user-task/user-task'
                });
              }, 1500);

            } catch (error) {
              // 错误处理
              uni.hideLoading();
              console.error('完成任务失败:', error);
              
              // 即使通知失败，只要任务状态更新成功也视为操作成功
              if (this.task.status === 'completed') {
                uni.showToast({
                  title: '任务已完成，但通知发布者失败',
                  icon: 'none'
                });
              } else {
                uni.showToast({
                  title: '完成任务失败: ' + (error.message || '未知错误'),
                  icon: 'none'
                });
              }
            }
          }
        }
      });
    },

    confirmClaimTask() {
      const currentUser = this.getCurrentUser();
      
      if (!currentUser || !currentUser.id) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      if (this.task.status !== 'pending') {
        uni.showToast({
          title: '任务状态已变更',
          icon: 'none'
        });
        return;
      }
      if (!this.canClaimTask) {
        uni.showToast({
          title: '您不能接此任务',
          icon: 'none'
        });
        return;
      }

      uni.showModal({
        title: '确认接单',
        content: '接单后即可查看发布者联系方式，确认接单后将无法取消，是否继续？',
        confirmText: '确认',
        cancelText: '取消',
        success: async (res) => {
          if (res.confirm) {
            try {
            console.log('调用接单API:', { taskId: this.task.id, userId: currentUser.id });
            
              // 调用云函数更新任务状态
              const result = await uniCloud.callFunction({
                name: 'updateTaskStatus',
                data: {
                  taskId: this.task.id,
                  status: 'processing',
                  receiverId: currentUser.id,
                  receiverName: currentUser.nickname || currentUser.username || '用户',
                  receiverAvatar: currentUser.avatar || '/static/images/default-avatar.png'
                }
              });

              if (result.result.code === 200) {
                // 接单成功后，重新从服务器获取任务详情
                await this.fetchTaskDetailFromServer(this.task.id);
            
            uni.showToast({
              title: '接单成功',
              icon: 'success',
              duration: 2000
            });
            
            try {
              const existingTasks = uni.getStorageSync('myTasks') || '[]';
              const tasks = JSON.parse(existingTasks);
              const taskIndex = tasks.findIndex(t => t.id === this.task.id);
              if (taskIndex !== -1) {
                    tasks[taskIndex] = this.task;
                uni.setStorageSync('myTasks', JSON.stringify(tasks));
              }
            } catch (error) {
                  console.error('更新本地任务状态失败', error);
            }
            
            setTimeout(() => {
              // 跳转到任务详情页面，刷新当前页面数据
              uni.navigateTo({
                url: '/pages/task/TaskDetail/TaskDetail?id=' + this.task.id
              });
            }, 1500);
              } else {
                throw new Error(result.result.msg || '接单失败');
              }
            } catch (error) {
              console.error('接单失败:', error);
              uni.showToast({
                title: '接单失败，请重试',
                icon: 'none'
              });
            }
          }
        }
      });
    },

    goBack() {
      uni.navigateBack();
    },

    async fetchTaskDetailFromServer(taskId) {
      try {
        console.log('从服务器获取任务详情:', taskId);
        
        const res = await uniCloud.callFunction({
          name: 'getTaskDetail',
          data: { taskId: taskId }
        });

        if (res.result.code === 200) {
          const taskData = res.result.data;
          console.log('获取到的任务详情:', taskData);
          console.log('[数据映射] publisher_id:', taskData.publisher_id);
          console.log('[数据映射] receiver_id:', taskData.receiver_id);
          console.log('[数据映射] acceptor_id:', taskData.acceptor_id);
          console.log('[数据映射] publisher_name:', taskData.publisher_name);
          console.log('[数据映射] receiver_name:', taskData.receiver_name);
          console.log('[数据映射] acceptor_name:', taskData.acceptor_name);
          console.log('[数据映射] 任务状态:', taskData.status);
          
          // 检查数据完整性
          if (!taskData.publisher_id) {
            console.warn('[数据映射] 警告：publisher_id 为空');
          }
          if (!taskData.receiver_id && !taskData.acceptor_id) {
            console.warn('[数据映射] 警告：receiver_id 和 acceptor_id 都为空');
          }
          
          // 将云函数返回的数据转换为页面需要的格式
          this.task = {
            id: taskData._id,
            type: taskData.type,
            title: taskData.title || taskData.type,
            description: taskData.description,
            reward: taskData.reward,
            status: taskData.status,
            publishTime: taskData.publish_time,
            expectedDeliveryTime: taskData.expected_time,
            pickupAddress: taskData.pickup_address,
            deliveryAddress: taskData.delivery_address,
            contactName: taskData.contact_name,
            contactPhone: taskData.contact_phone,
            publisher: taskData.publisher_id ? {
              id: taskData.publisher_id,
              nickname: taskData.publisher_name,
              avatar: taskData.publisher_avatar
            } : null,
            receiver: (taskData.receiver_id || taskData.acceptor_id) ? {
              id: taskData.receiver_id || taskData.acceptor_id,
              nickname: taskData.receiver_name || taskData.acceptor_name || '接单者',
              avatar: taskData.receiver_avatar || taskData.acceptor_avatar || '/static/images/default-avatar.png'
            } : null,
            tags: taskData.tags || [],
            images: taskData.images || [],
            isUrgent: taskData.is_urgent || false,
            acceptTime: taskData.accept_time,
            completeTime: taskData.complete_time,
            cancelTime: taskData.cancel_time,
            trackingNumber: taskData.tracking_number,
            selectedCondition: taskData.selected_condition,
            itemName: taskData.item_name,
            selectedCategory: taskData.selected_category,
            // 进度相关字段
            progressStep: taskData.progress_step || 1,
            progressText: taskData.progress_text || '',
            latestUpdate: taskData.latest_update || '',
            updateTime: taskData.update_time
          };
          
          // 使用 $nextTick 确保数据完全更新后再进行角色判断
          this.$nextTick(() => {
            console.log('[数据更新] 接单者信息更新后:');
            console.log('[数据更新] receiver对象:', this.task.receiver);
            console.log('[数据更新] receiver.id:', this.task.receiver?.id);
            console.log('[数据更新] receiver.nickname:', this.task.receiver?.nickname);
            console.log('[数据更新] publisher对象:', this.task.publisher);
            console.log('[数据更新] publisher.id:', this.task.publisher?.id);
            console.log('[数据更新] publisher.nickname:', this.task.publisher?.nickname);
            console.log('[数据更新] 当前用户ID:', this.getCurrentUser()?.id);
            
            // 强制重新判断角色
            console.log('[数据更新] 强制重新判断角色...');
            this.determineUserRole();
            
            // 延迟再次判断，确保数据完全更新
            setTimeout(() => {
              console.log('[数据更新] 延迟重新判断角色...');
              this.determineUserRole();
            }, 100);
          });
          
          // 如果是进行中状态，使用服务端返回的进度或计算进度
          if (this.isProcessing) {
            // 优先使用服务端返回的进度，如果没有则计算
            this.progressStep = taskData.progress_step || this.getProgressStep();
          }
        } else {
          console.error('获取任务详情失败:', res.result.msg);
          uni.showToast({
            title: res.result.msg || '获取任务详情失败',
            icon: 'error'
          });
        }
      } catch (error) {
        console.error('获取任务详情异常:', error);
        uni.showToast({
          title: '获取任务详情失败',
          icon: 'error'
        });
      }
    },

    formatPublishTime(time) {
      if (!time) return '';
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    formatTime(time) {
      if (!time) return '';
      return this.formatPublishTime(time);
    },

    // 新增状态相关方法
    getRemainingTime() {
      if (!this.task.expectedDeliveryTime || this.isCompleted || this.isCancelled) {
        return '未设置时间';
      }
      
      const expectedTime = new Date(this.task.expectedDeliveryTime);
      const now = new Date();
      const diff = expectedTime - now;
      
      if (diff <= 0) return '已超时';
      
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      
      if (hours > 0) {
        return `${hours}小时${minutes}分钟后结束`;
      } else {
        return `${minutes}分钟后结束`;
      }
    },
    
    formatStatusTime() {
      if (this.isPending) return '发布于 ' + this.formatPublishTime(this.task.publishTime);
      if (this.isProcessing) return '接单于 ' + this.formatTime(this.task.acceptTime);
      if (this.isPendingReview) return '提交验收于 ' + this.formatTime(this.task.submitTime);
      if (this.isCompleted) return '完成于 ' + this.formatTime(this.task.completeTime);
      if (this.isCancelled) return '取消于 ' + this.formatTime(this.task.cancelTime);
      return '';
    },

    // 优化状态变更处理
    handleStatusChange(newStatus) {
      uni.showLoading({ title: '更新状态中...' });
      // 调用云函数更新状态
      uniCloud.callFunction({
        name: 'updateTaskStatus',
        data: {
          taskId: this.task.id,
          status: newStatus
          // 其他必要参数
        }
      }).then(res => {
        uni.hideLoading();
        if (res.result.code === 200) {
          // 更新本地任务状态
          this.task.status = newStatus;
          // 状态变化可能伴随角色相关字段变化（如取消后 receiver 清空）
      this.determineUserRole();
          if (newStatus === 'processing') {
            this.task.acceptTime = new Date().toISOString();
          }
          if (newStatus === 'completed') {
            this.task.completeTime = new Date().toISOString();
          }
          if (newStatus === 'cancelled') {
            this.task.cancelTime = new Date().toISOString();
          }
          uni.showToast({
            title: '状态更新成功',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: res.result.msg || '状态更新失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        uni.hideLoading();
        console.error('状态更新异常:', err);
        uni.showToast({
          title: '状态更新失败，请重试',
          icon: 'none'
        });
      });
    },

    // 进行中状态相关方法
    getProgressStep() {
      // 根据任务状态和时间计算进度
      if (!this.task.acceptTime || !this.task.expectedDeliveryTime) return 1;
      
      const acceptTime = new Date(this.task.acceptTime);
      const expectedTime = new Date(this.task.expectedDeliveryTime);
      const now = new Date();
      
      const totalDuration = expectedTime - acceptTime;
      const elapsedDuration = now - acceptTime;
      
      if (elapsedDuration <= 0) return 1;
      if (elapsedDuration >= totalDuration) return this.taskSteps.length;
      
      // 按时间比例计算进度
      const progressRatio = elapsedDuration / totalDuration;
      return Math.min(1 + Math.floor(progressRatio * (this.taskSteps.length - 1)), this.taskSteps.length);
    },

    async updateProgress() {
      // 身份校验
      if (!this.isClaimer) {
        uni.showToast({ title: '只有接单者才能更新进度', icon: 'none' });
        return;
      }

      // 进度边界校验
      if (this.progressStep >= this.taskSteps.length) {
        uni.showToast({ title: '任务进度已完成', icon: 'none' });
        return;
      }

      // 显示加载状态
      uni.showLoading({ title: '更新进度中...' });

      try {
        // 计算新进度
        const newProgressStep = this.progressStep + 1;
        const progressText = this.taskSteps[newProgressStep - 1].text;
        const currentUser = this.getCurrentUser();

        // 用户信息校验
        if (!currentUser || !currentUser.id) {
          throw new Error('用户信息获取失败，请重新登录');
        }

        // 调用云函数同步进度
        const cloudRes = await uniCloud.callFunction({
          name: 'updateTaskProgress',
          data: {
            taskId: this.task.id,
            progressStep: newProgressStep,
            progressText: progressText,
            userId: currentUser.id // 传递当前用户 ID
          }
        });

        // 云函数返回结果校验
        if (cloudRes.result.code !== 200) {
          throw new Error(cloudRes.result.msg || '进度更新失败');
        }

        // 云函数成功后，再更新本地状态
        this.progressStep = newProgressStep;

        uni.hideLoading();
        uni.showToast({
          title: `已更新到：${progressText}`,
          icon: 'success'
        });

        // 进度到最后一步时，触发完成任务
        if (this.progressStep === this.taskSteps.length) {
          setTimeout(() => {
            this.completeTask();
          }, 1000);
        }
      } catch (error) {
        uni.hideLoading();
        console.error('更新进度失败:', error);
        uni.showToast({
          title: error.message || '进度更新失败，请重试',
          icon: 'none'
        });
      }
    },

    contactPublisher() {
      if (!this.isClaimer) {
        uni.showToast({
          title: '只有接单者才能联系发布者',
          icon: 'none'
        });
        return;
      }
      if (!this.task.contactPhone) {
        uni.showToast({
          title: '未获取到联系方式',
          icon: 'none'
        });
        return;
      }
      
      uni.makePhoneCall({
        phoneNumber: this.task.contactPhone,
        fail: () => {
          uni.showToast({
            title: '拨打电话失败',
            icon: 'none'
          });
        }
      });
    },

    // 评价相关方法
    showEvaluateDialog() {
      const userInfo = uni.getStorageSync('uni-id-pages-userInfo');
      if (!userInfo || !userInfo._id) {
        uni.showToast({ title: '请先登录再评价', icon: 'none' });
        return;
      }
      
      // 只有发布者可以评价，且任务状态为待验收
      if (!this.isPublisher) {
        uni.showToast({ title: '只有发布者可以评价任务', icon: 'none' });
        return;
      }
      
      if (!this.isPendingReview) {
        uni.showToast({ title: '任务状态不允许评价', icon: 'none' });
        return;
      }
      
      this.showEvaluate = true;
    },

    async submitEvaluation() {
  if (this.rating < 1) {
    uni.showToast({
      title: '请给出评价星级',
      icon: 'none'
    });
    return;
  }
  
  // 新增：校验任务ID是否存在
  if (!this.task || !this.task.id) {
    uni.showToast({
      title: '任务信息不完整，无法评价',
      icon: 'none'
    });
    return;
  }
  
  // 显示加载状态
  uni.showLoading({ title: '提交评价中...' });
  
  try {
    // 1. 从缓存获取用户信息（关键：获取用户ID）
    const userInfo = uni.getStorageSync('uni-id-pages-userInfo');
    if (!userInfo || !userInfo._id) {
      throw new Error('用户未登录或登录状态失效，请重新登录');
    }
    const userId = userInfo._id; // 提取用户ID
    
    // 2. 调用云函数：补充传递userId参数（核心修复点）
    const result = await uniCloud.callFunction({
      name: 'submitEvaluation',
      data: {
        taskId: this.task.id,    // 任务ID（已有）
        rating: this.rating,     // 评价星级（已有）
        content: this.evaluationContent, // 评价内容（已有）
        userId: userId           // 新增：传递用户ID，满足云函数校验要求
      }
    });
    
    // 隐藏加载状态
    uni.hideLoading();
    
    // 3. 处理云函数返回结果
    if (result.result && result.result.code === 200) {
      this.evaluated = true;
      this.showEvaluate = false;
      
      // 评价成功后，任务状态已经在 submitEvaluation 云函数中更新为 completed
      // 收入结算也已经在 submitEvaluation 云函数中处理完成
      // 只需要更新本地状态
      this.task.status = 'completed';
      this.task.completeTime = new Date().toISOString();
      this.determineUserRole();
      
      uni.showToast({
        title: '评价提交成功，任务已完成',
        icon: 'success',
        duration: 2000
      });
      
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/user/user-task/user-task'
        });
      }, 1500);
    } else {
      // 处理业务逻辑错误（如权限不足、任务不存在等）
      uni.showToast({
        title: result.result?.msg || '评价提交失败',
        icon: 'none'
      });
    }
  } catch (error) {
    // 隐藏加载状态
    uni.hideLoading();
    
    // 处理调用错误（如网络错误、用户未登录等）
    console.error('提交评价失败:', error);
    
    // 针对性错误提示
    if (error.message.includes('未登录')) {
      uni.showToast({
        title: error.message,
        icon: 'none'
      });
      // 可选：跳转至登录页
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/login/login' });
      }, 1500);
    } else if (error.message.includes('fc_function_not_found')) {
      uni.showToast({
        title: '评价功能未开通，请联系管理员',
        icon: 'none'
      });
    } else {
      uni.showToast({
        title: '网络错误，请稍后重试',
        icon: 'none'
      });
    }
  }
},

    // 开始倒计时
    startCountdown() {
      if (!this.task.expectedDeliveryTime || this.timer) return;
      
      this.timer = setInterval(() => {
        const remainingTime = this.getRemainingTime();
        if (remainingTime === '已超时') {
          this.stopCountdown();
          uni.showModal({
            title: '任务超时',
            content: '您的任务已超过预计完成时间，是否继续处理？',
            confirmText: '继续处理',
            cancelText: '取消任务',
            success: (res) => {
              if (res.confirm) {
                // 继续处理逻辑
              } else {
                this.cancelTask();
              }
            }
          });
        } else if (remainingTime.includes('1小时') || remainingTime.includes('30分钟')) {
          // 关键时间点提醒
          uni.showToast({
            title: `注意：任务将在${remainingTime}后超时`,
            icon: 'none'
          });
        }
      }, 60000); // 每分钟检查一次
    },

    // 停止倒计时
    stopCountdown() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

  },

  onLoad(options) {
    console.log('[页面加载] 参数:', options);
    
    const currentUser = this.getCurrentUser();
    console.log('[页面加载] 获取到的当前用户:', currentUser);

    if (options.taskInfo) {
      try {
        const taskInfo = JSON.parse(decodeURIComponent(options.taskInfo));
        console.log('[页面加载] 解析后的任务信息:', taskInfo);
        
        this.task = taskInfo;
        this.determineUserRole();
        
      } catch (error) {
        console.error('[页面加载] 解析任务信息失败:', error);
        uni.showToast({
          title: '获取任务信息失败',
          icon: 'error'
        });
      }
    } else if (options.id) {
      this.taskId = options.id;
      console.log('[页面加载] 任务ID:', this.taskId);
      
      // 调用云函数获取任务详情
      this.fetchTaskDetailFromServer(this.taskId);
      
      // 获取通过eventChannel传递的数据
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.on('taskData', (data) => {
        this.taskData = data.task;
        console.log('[页面加载] 从index页面接收到的任务数据:', this.taskData);
        // 将接收到的数据赋值给task
        if (this.taskData) {
          this.task = this.taskData;
          // 如果从index页面传递的数据不完整，重新从服务器获取
          if (!this.task.publisher || !this.task.publisher.id) {
            console.log('[页面加载] 任务数据不完整，重新从服务器获取');
            this.fetchTaskDetailFromServer(this.taskId);
          } else {
            this.determineUserRole();
          }
        }
      });
    } else {
      console.log('[页面加载] 没有任务信息，创建默认任务');
      const currentUser = this.getCurrentUser();
      
      let defaultTask = {
        id: 'default_task_id',
        type: 'express',
        status: 'pending',
        title: '默认代取快递任务',
        description: '这是一个默认的测试任务',
        reward: 5,
        publishTime: new Date().toLocaleString(),
        expectedDeliveryTime: new Date(Date.now() + 3600000).toLocaleString(), // 1小时后
        pickupAddress: '学校快递站',
        deliveryAddress: '宿舍楼',
        trackingNumber: '1234567890',
        contactName: '张三',
        contactPhone: '13800138000',
        publisher: null,
        receiver: null
      };

      if (currentUser && currentUser.id) {
        defaultTask.publisher = {
          id: currentUser.id,
          nickname: currentUser.nickname,
          avatar: currentUser.avatar,
          creditRating: 4.5
        };
        } else {
        defaultTask.publisher = { id: 'default_publisher', nickname: '默认发布者', avatar: '/static/images/avatar1.png', creditRating: 4.5 };
      }
      
      this.task = defaultTask;
      this.determineUserRole();
    }
  },

  onShow() {
  // 页面显示时，重新判断角色（应对登录状态变化）
  this.determineUserRole();
  // ... 原有倒计时逻辑 ...
  if (this.isProcessing && !this.timer) {
    this.startCountdown();
  }
},

  onHide() {
    this.stopCountdown();
  },

  onUnload() {
    this.stopCountdown();
  },

  watch: {
    // 任务数据变化时，重新判断角色
  task: {
    deep: true, // 深度监听（如 task.receiver 变化）
    handler() {
      console.log('[watch] 任务数据变化，重新判断角色');
      this.determineUserRole();
    }
  },
  // 角色变化时，同步更新按钮状态（避免样式错乱）
  currentUserRole() {
    console.log('[watch] 角色变化，强制刷新UI');
    this.$forceUpdate();
  },
    taskStatus(newStatus, oldStatus) {
      console.log(`任务状态变更: ${oldStatus} -> ${newStatus}`);
      if (newStatus === 'processing' && oldStatus === 'pending') {
        uni.showToast({
          title: '已成功接单，开始处理任务吧',
          icon: 'success'
        });
        this.startCountdown();
        this.progressStep = 1;
      }
      // 【修改点5】只有发布者在任务完成时才显示评价提示
      if (newStatus === 'completed' && this.isPublisher) {
        this.stopCountdown();
        this.$nextTick(() => {
          uni.showToast({
            title: '任务已完成，您可以进行评价',
            icon: 'none',
            duration: 3000
          });
        });
      }
      if (newStatus === 'cancelled') {
        this.stopCountdown();
      }
    }
  }
}
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: 20rpx;
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
}

/* 状态提示区域样式 */
.status-tip-area {
  padding: 20rpx 30rpx;
  background-color: #f9fafc;
  border-radius: 20rpx;
  margin: 20rpx 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.status-tip {
  display: flex;
  align-items: center;
  gap: 12rpx;
  font-size: 28rpx;
  color: #333;
}

.status-icon {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
}

.status-icon.pending { background-color: #E6F7FF; color: #1890FF; }
.status-icon.processing { background-color: #FFF7E6; color: #FA8C16; }
.status-icon.pending_review { background-color: #F0F5FF; color: #722ED1; }
.status-icon.completed { background-color: #F6FFED; color: #52C41A; }
.status-icon.cancelled { background-color: #FFF1F0; color: #F5222D; }

.status-text { font-weight: bold; }
.time-left { color: #fa8c16; margin-left: auto; }

.status-time {
  font-size: 24rpx;
  color: #999;
  margin: -10rpx 30rpx 20rpx;
  text-align: right;
}

/* 待验收状态提示样式 */
.review-tip {
  background: linear-gradient(135deg, #F0F5FF, #E6F7FF);
  border: 1rpx solid #722ED1;
  border-radius: 12rpx;
  padding: 20rpx 30rpx;
  margin: 20rpx 30rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.tip-icon {
  font-size: 32rpx;
}

.tip-text {
  font-size: 28rpx;
  color: #722ED1;
  font-weight: 500;
}

/* 任务信息区域样式 */
.task-info, .description-section, .address-section, .publisher-section, .processing-area {
  border-radius: 20rpx;
  margin: 0 30rpx 30rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  background-color: #ffffff;
  padding: 30rpx;
}

/* 图片轮播区域 */
.image-slider {
  width: calc(100% - 60rpx);
  height: 500rpx;
  margin: 0 30rpx 30rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.image-slider swiper {
  width: 100%;
  height: 100%;
}

.image-slider swiper-item {
  width: 100%;
  height: 100%;
}

.slider-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.task-info {
 padding: 40rpx;
  background: linear-gradient(145deg, #ffffff, #f5f7fa);
}

.task-header-flex {
  padding: 0 0 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.task-title {
  font-size: 36rpx;
  font-weight: bold;
  line-height: 1.5;
  color: #1a1a1a;
  width: 100%;
  text-align: center;
  margin-bottom: 20rpx;
}

/* 任务类型和状态标签容器*/
.task-type-container {
  display: flex;
  justify-content: center;
  width: 100%;
  margin-top: 10rpx;
}

.task-type {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 16rpx;
  align-items: center;
}

/* 类型标签基础样式 */
.type-tag {
  padding: 8rpx 20rpx;
  border-radius: 32rpx;
  font-size: 26rpx;
  display: inline-flex;
  align-items: center;
  gap: 6rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

/* 加急标签样式*/
.urgent-tag {
  padding: 6rpx 16rpx;
  border-radius: 32rpx;
  font-size: 24rpx;
  background: linear-gradient(135deg, #FF4D4F 0%, #FF7875 100%);
  color: #ffffff;
  display: inline-flex;
  align-items: center;
  box-shadow: 0 2rpx 8rpx rgba(255, 77, 79, 0.2);
}

/* 任务状态标签样式*/
.task-status-tag {
  padding: 8rpx 20rpx;
  border-radius: 32rpx;
  font-size: 24rpx;
  display: inline-flex;
  align-items: center;
  gap: 6rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

/* 状态标签颜色*/
.task-status-tag.pending {
  background-color: #E6F7FF;
  color: #1890FF;
}

.task-status-tag.processing {
  background-color: #FFF7E6;
  color: #FA8C16;
}

.task-status-tag.pending_review {
  background-color: #F0F5FF;
  color: #722ED1;
}

.task-status-tag.completed {
  background-color: #F6FFED;
  color: #52C41A;
}

.task-status-tag.cancelled {
  background-color: #FFF1F0;
  color: #F5222D;
}

/* 类型标签颜色 */
.type-tag.buy {
  background-color: #E6F7FF;
  color: #1890FF;
}

.type-tag.sell {
  background-color: #F6FFED;
  color: #52C41A;
}

.type-tag.takeout {
  background-color: #FFF7E6;
  color: #FA8C16;
}

.type-tag.express {
  background-color: #F9F0FF;
  color: #722ED1;
}

.type-tag.other {
  background-color: #F5F5F5;
  color: #666666;
}

.task-time, .task-reward {
  display: flex;
  align-items: center;
  gap: 12rpx;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.task-time .time-label, 
.task-reward .reward-label,
.address-label {
  color: #999;  /* 标签颜色改为灰色 */
  font-weight: normal;
  min-width: 140rpx;  /* 固定标签宽度 */
}
.time-value, 
.reward-value,
.address-text {
  color: #333;  /* 值颜色改为深灰色 */
  flex: 1;
}
.reward-value {
  color: #ff3b30;
    font-weight: bold;
    font-size: 32rpx;
}

/* 描述区域样式 */
.description-section {
  padding: 40rpx;
   background-color: #ffffff;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
  padding-bottom: 15rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.description-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

/* 地址信息区域样式 */
.address-section {
  background-color: #fff;
  padding: 30rpx;
  margin: 20rpx 30rpx;
  border-radius: 20rpx;
}

.address-item {
  margin-bottom: 30rpx;
  padding-bottom: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  flex-direction: column;
}

.address-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.address-label {
  margin-bottom: 10rpx;
  font-size: 28rpx;
  color: #999;
  flex-basis: auto;
}

.address-content {
  flex: 1;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15rpx;
}

.address-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  flex: 1;
}

.copy-btn, .nav-btn {
  padding: 8rpx 20rpx;
  font-size: 24rpx;
  border-radius: 8rpx;
  height: auto;
  line-height: normal;
  margin-left: 10rpx;
}

.copy-btn {
  background-color: #f5f5f5;
  color: #666;
}

.nav-btn {
  background-color: #e6f7ff;
  color: #1890ff;
}

/* 发布者信息区域样式*/
.publisher-section {
  background-color: #fff;
  padding: 30rpx;
  margin: 20rpx 30rpx;
  border-radius: 20rpx;
}

.publisher-info {
  margin-bottom: 20rpx;
}

.publisher-details {
  padding: 30rpx;
  background-color: #f9fafc;
  border-radius: 16rpx;
}

.publisher-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.publisher-name {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.publisher-rating {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.contact-info {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

/* 进行中状态区域样式 */
.processing-area {
  background-color: #fff;
  padding: 30rpx;
  margin: 20rpx 30rpx;
  border-radius: 20rpx;
}

.progress-steps {
  display: flex;
  justify-content: space-between;
  margin: 40rpx 0;
  position: relative;
  padding: 0 10rpx;
}

/* 灰色背景条 */
.progress-steps::before {
  content: '';
  position: absolute;
  top: 30rpx;
  left: 50rpx;
  right: 50rpx;
  height: 6rpx;
  background-color: #eee;
  z-index: 1;
}

/* 绿色进度条 */
.progress-steps::after {
  content: '';
  position: absolute;
  top: 30rpx;
  left: 50rpx;
  height: 6rpx;
  width: var(--progress-width, 0%);
  background: linear-gradient(90deg, #52c41a, #73d13d);
  z-index: 2;
  transition: width 0.3s ease;
  border-radius: 3rpx;
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 3;
  width: 20%;
}

.step-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #eee;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
  margin-bottom: 15rpx;
}

.step-text {
  font-size: 24rpx;
  color: #999;
  text-align: center;
  word-break: break-all;
}

.step-item.active .step-icon {
  background: linear-gradient(135deg, #52c41a, #73d13d);
  color: white;
  box-shadow: 0 2rpx 8rpx rgba(82, 196, 26, 0.3);
}

.step-item.active .step-text {
  color: #52c41a;
  font-weight: bold;
}

.task-specific-info {
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  font-size: 26rpx;
  color: #666;
  min-width: 120rpx;
  margin-right: 15rpx;
}

.info-value {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  flex: 1;
}

.progress-actions {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
  margin-top: 30rpx;
}

/* 底部操作栏样式*/
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  display: flex;
  align-items: center;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.action-buttons {
  flex: 1;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  gap: 20rpx;
  align-items: center;
}

.action-button {
  min-width: 180rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: bold;
  padding: 0 30rpx;
}

.action-button.confirm {
  background: linear-gradient(135deg, #00BFFF, #0099FF);
  color: #fff;
}

.action-button.ignore {
  background-color: #f5f5f5;
  color: #666;
}

.action-button.start {
  background: linear-gradient(135deg, #00BFFF, #0099FF);
  color: #fff;
}

.action-button.cancel {
  background: linear-gradient(135deg, #FF4D4F, #FF7875);
  color: #fff;
}

.action-button.complete {
  background: linear-gradient(135deg, #52C41A, #73D13D);
  color: #fff;
}

.action-button.update {
  background: linear-gradient(135deg, #FA8C16, #FFA94D);
  color: #fff;
}

.action-button.contact {
  background: linear-gradient(135deg, #722ED1, #9E55FC);
  color: #fff;
}
/* 发布者专属按钮样式 */
.action-button.remind {
  background: linear-gradient(135deg, #FA8C16, #FFA94D);
  color: #fff;
}
.action-button.view-claimer {
  background: linear-gradient(135deg, #722ED1, #9E55FC);
  color: #fff;
}
.action-button.evaluate {
  background: linear-gradient(135deg, #1890FF, #40A9FF);
  color: #fff;
}

.urgent-tag {
 font-size: 22rpx;
  padding: 6rpx 12rpx;
}

.privacy-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 20rpx;
  line-height: 1.5;
  display: block;
}

/* 评价弹窗样式 */
.evaluate-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 30rpx;
}

.modal-content {
  background-color: white;
  border-radius: 20rpx;
  width: 100%;
  max-width: 600rpx;
  padding: 40rpx;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  text-align: center;
  color: #333;
}

.star-rating {
  display: flex;
  justify-content: center;
  gap: 15rpx;
  margin-bottom: 30rpx;
}

.star {
  font-size: 50rpx;
  color: #ddd;
}

.star.selected {
  color: #FA8C16;
}

.evaluate-input {
  width: 100%;
  height: 200rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
  margin-bottom: 30rpx;
  box-sizing: border-box;
}

.modal-buttons {
  display: flex;
  gap: 20rpx;
}

.modal-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.modal-btn.cancel {
  background-color: #f5f5f5;
  color: #666;
}

.modal-btn.confirm {
  background-color: #1890ff;
  color: white;
}


/* 适配 iPhone 安全区域 */
@supports (padding-bottom: env(safe-area-inset-bottom)) {
  .container {
    padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
  }
  
  .bottom-bar {
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  }
}
</style>
